package com.aistar.model.bo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/web/{id}")
public class WebSocketProcess {
    public static ConcurrentHashMap<Long,WebSocketProcess> concurrentHashMap = new ConcurrentHashMap<>(12);

    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("id")long id){
     this.session = session;
     concurrentHashMap.put(id,this);
     log.info("Open a websocket.id = {}",id);
    }
    @OnOpen
    public void onClose(Session session,@PathParam("id")long id){
        concurrentHashMap.remove(id);
        log.info("close a websocket,concurrentHashMap remove sessionId = {}",id);
    }

    @OnMessage
    public void onMessage(String message,@PathParam("id")String id){
        log.info("receive a message from client id = {},msg={}",id,message);
    }

    @OnError
    public void onError(Session session,Throwable error){
        log.error("Error while websocket.",error);
    }

    public void sendMessage(long id,String message) throws Exception{
        WebSocketProcess webSocketProcess = concurrentHashMap.get(id);
        if(!ObjectUtils.isEmpty(webSocketProcess)){
            if(webSocketProcess.session.isOpen()){
                webSocketProcess.session.getBasicRemote().sendText(message);
            }else{
                log.error("websocket session = {} is closed",id);
            }
        }else{
            // log.error("websocket session = {} is not exit",id);
        }
    }

    public void sendAllMessage(String msg) throws Exception{
        log.info("online client count={}",concurrentHashMap.size());
        Set<Map.Entry<Long,WebSocketProcess>> entries = concurrentHashMap.entrySet();
        for(Map.Entry<Long,WebSocketProcess>entry:entries){
            Long cid = entry.getKey();
            WebSocketProcess webSocketProcess = entry.getValue();
            boolean sessionOpen = webSocketProcess.session.isOpen();
            if(sessionOpen){
                webSocketProcess.session.getBasicRemote().sendText(msg);
            }else{
                log.info("cid={} is closed,ignore send text",cid);
            }
        }
    }
}
